<!-- 表格 -->
<template>
  <div class="row">
    
    <el-select class="ml-10" v-model="tag" clearable placeholder="标签">
      <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id">
      </el-option>
    </el-select>
    <el-select class="ml-10" v-model="statu" clearable placeholder="状态">
      <el-option v-for="item in status" :key="item.value" :label="item.label" :value="item.value">
      </el-option>
    </el-select>
    <el-autocomplete class="ml-10" v-model="state" :fetch-suggestions="querySearchAsync" placeholder="搜索标题" @select="handleSelect">
    </el-autocomplete>
    <el-button class="ml-10" icon="el-icon-search" circle :loading="isSearch" @click="search()"></el-button>
    <div class="col-12">
      <el-table :data="tableDataNew" style="width: 100%" v-loading="isSearch">
        <el-table-column label="ID" width="100px;">
          <template slot-scope="scope">
            <span style="margin-left: 10px">{{ scope.row.id }}</span>
          </template>
        </el-table-column>

        <el-table-column label="标题" width="300px">
          <template slot-scope="scope">
            <search-highlight class="search-highlight" ref="search" @current-change="currentChange(scope.row.id)" highlightStyle="color:red" currentStyle=""
              @mactch-count-change="matchCountChange" :content="scope.row.title" :keyword="state">
            </search-highlight>
            <!-- <span style="margin-left: 10px">{{ scope.row.title }}</span> -->
          </template>
        </el-table-column>

        <el-table-column label="标签" width="250px">
          <template slot-scope="scope">
            <el-tag class="ml-5" v-for="tag in scope.row.tag.split('-')" :key="tag" disable-transitions v-if="tag!=''">
              {{ tagFormat(tag) }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="日期" width="180px">
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            <span style="margin-left: 10px">{{ $commons.dateStr(scope.row.updatetime) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="状态" width="80px">
          <template slot-scope="scope">
            <el-tag class="ml-5" :type="scope.row.status === 'DRAFT' ? 'warning' : 'success'" disable-transitions>
              {{ scope.row.status=='DRAFT'?'草稿':scope.row.status=='TOP'?'置顶':'发布' }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>

            <el-button size="mini" :type="scope.row.status == 'DRAFT' ? 'warning' : 'success'"
              @click="setStatus(scope.row, scope.row.status == 'DRAFT' ?'RELEASE':'DRAFT')">
              {{scope.row.status == 'DRAFT' ? '发布' : '存稿'}}</el-button>
            <el-popconfirm title="删除后不可恢复，确定要删除吗？" @confirm="remove(scope.row)">
              <el-link icon="el-icon-delete" slot="reference"></el-link>
            </el-popconfirm>
              <el-link :icon="isAsync == scope.row.id?'el-icon-loading':'el-icon-refresh'" slot="reference" @click="asyncDoc(scope.row.id)"></el-link>
          </template>
        </el-table-column>

      </el-table>

    </div>
    <div class="col-12">
      <el-pagination style="float:left;" layout="prev, pager, next" :total="total" :current-page="currentPage"
        @current-change="pageChange">
      </el-pagination>
    </div>
  </div>

</template>

<script>
  //这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
  //例如：import 《组件名称》 from '《组件路径》';
  import SearchHighlight from 'vue-search-highlight'
  export default {
    //import引入的组件需要注入到对象中才能使用
    components: {
      'search-highlight': SearchHighlight
    },
    data() {
      //这里存放数据
      return {
        isAsync:-1,
        currentIdx: 0,
        matchCount: 0,
        isSearch: false,
        statu: '',
        tag: '',
        status: [{
          value: 'TOP',
          label: '置顶'
        }, {
          value: 'RELEASE',
          label: '发布'
        }, {
          value: 'DRAFT',
          label: '草稿'
        }],
        options: [],
        value: [],
        restaurants: [],
        state: '',
        currentPage: 1,
        total: 0,
        tableData: []

      };
    },
    //监听属性 类似于data概念
    computed: {
            tableDataNew: function () {
        return this.tableData.filter((data) => {
          return data.title.toLowerCase().indexOf(this.state.toLowerCase()) != -1
        })
      }
    },
    //监控data中的数据变化
    watch: {
      
    },
    //方法集合
    methods: {
      async asyncDoc(id) {
        this.isAsync = id;
        var ids = [];
        ids.push(id);
        const pram = {
          ids:[id]
        }
       var res = await this.$api.core.async(pram);
       if (res.code == 20000) {
         Notiflix.Notify.Info('同步结果 成功ID：'+res.data.success+' 失败：'+res.data.failed);
       }
       this.isAsync = -1;
      },
      searchNext() {
        this.$refs.search.searchNext()
      },
      searchLast() {
        this.$refs.search.searchLast()
      },
      matchCountChange(count) {
        this.matchCount = count
      },
      currentChange(idx) {
        this.currentIdx = idx
      },
      checkKeydown(event) {
        if (event.shiftKey) {
          this.searchLast()
        } else {
          this.searchNext()
        }
      },

      async setStatus(data, status) {
        this.isSearch = true;
        const pram = {
          status: status,
          id: data.id
        }
        var res = await this.$api.core.setDocumentStatus(pram);
        if (res.code == 6000) {
          this.search();
        }
        this.isSearch = false
      },
      async remove(data) {
        this.isSearch = true;
        const pram = {
          id: data.id
        }
        var res = await this.$api.core.removeDocument(pram);
        if (res.code == 6000) {
          this.search();
        }
        this.isSearch = false;
      },
      handleEdit(data) {
        this.$parent.docId = data.id;
        this.$parent.option = 5;
      },
      tagFormat(tag) {
        for (const t of this.options) {
          if (t.id == tag)
            return t.name;
        }
      },
      async search(page=false) {
        this.isSearch = true;
        const pram = {
          page: {
            current: page?this.currentPage:1
          },
          document: {
            title: this.$commons.isEmptyString(this.state) ? null : this.state,
            tag: this.$commons.isEmptyString(this.tag + '') ? null : this.tag + '-',
            status: this.$commons.isEmptyString(this.statu) ? null : this.statu
          }
        }
        var res = await this.$api.core.documentList(pram);
        if (res.code == 20000) {
          this.tableData = res.data.records;
          this.total = res.data.total;
        }
        this.isSearch = false;
      },
      async getTag() {
        var res = await this.$api.core.getTags();
        this.options = res.data;
      },
      async querySearchAsync(queryString, cb) {
        if (this.$commons.isEmptyString(queryString)) {
          return
        }
        // 在这里通过queryString去后端查询数据
        // cb(res)回调显示查询结果
        const pram = {
          title: queryString
        }
        var res = await this.$api.search.searchUserTitle(pram);
        var rs = [];
        if (res.code == 20000) {
          for (const r of res.data) {
            rs.push({
              value: r.title,
              id: r.id
            });

          }
          cb(rs)
        }

        // var restaurants = this.restaurants;
        // var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;

        // clearTimeout(this.timeout);
        // this.timeout = setTimeout(() => {
        //   cb(results);
        // }, 3000 * Math.random());
      },
      createStateFilter(queryString) {
        return (state) => {
          return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },
      handleSelect(item) {
        this.search();
      },
      pageChange(page) {
        this.currentPage = page;
        this.search(true);
      },

    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {

    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {
      this.getTag();
      this.search();
    },
    beforeCreate() {}, //生命周期 - 创建之前
    beforeMount() {}, //生命周期 - 挂载之前
    beforeUpdate() {}, //生命周期 - 更新之前
    updated() {}, //生命周期 - 更新之后
    beforeDestroy() {}, //生命周期 - 销毁之前
    destroyed() {}, //生命周期 - 销毁完成
    activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
  }

</script>
<style>

</style>
